package com.server.file.service.impl;


import com.server.file.constants.CommonConstants;
import com.server.file.dao.DataFileRepository;
import com.server.file.dto.Result;
import com.server.file.model.DataFile;
import com.server.file.service.DataFileService;
import com.server.file.support.FastDFSClientWrapper;
import com.server.file.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by wt on 2018/11/30.
 */
@Service
public class DataFileServiceImpl implements DataFileService {

    private static Logger logger = LoggerFactory.getLogger(DataFileServiceImpl.class);

    @Autowired
    private DataFileRepository dataFileRepository;

    @Autowired
    private FastDFSClientWrapper dfsClient;

    @Override
    public DataFile findOne(Long id) {
        return dataFileRepository.getOne(id);
    }

    @Override
    @Transactional
    public void doSave(DataFile ds) {
        dataFileRepository.save(ds);
    }

    @Override
    @Transactional
    public Result doDelete(List<Long> ids) {
        List<DataFile> files = dataFileRepository.findByIdIn(ids);
        for (DataFile file : files) {
            // 删除服务器上的文件
            Result result = dfsClient.deleteFile(file.getPath());
            if(result.getCode().equals(CommonConstants.SUCCESS)){
                // 文件删除成功后删除文件记录
                dataFileRepository.deleteById(file.getId());
            }else{
                return result;
            }
        }
        return ResultUtil.success();
    }
}
